import { debounce } from './util.js'
import Vue from 'vue'
import { base64ToPath, pathToBase64 } from '@/utils/image-tools'
import moment from 'moment'
import html2canvas from 'html2canvas'
import { gcj02_To_gps84 } from '@/utils/changLatLon'
function transformFromGCJToWGS(lon, lat) {
	var a = 6378245.0
	var ee = 0.00669342162296594323

	function outOfChina(lon, lat) {
		if (lon < 72.004 || lon > 137.8347) {
			return true
		}
		if (lat < 0.8293 || lat > 55.8271) {
			return true
		}
		return false
	}

	function transformLon(x, y) {
		var pi = Math.PI
		var ret = 300.0 + x + 2.0 * y + 0.1 * x * x + 0.1 * x * y + 0.1 * Math.sqrt(Math.abs(x))
		ret += ((20.0 * Math.sin(6.0 * x * pi) + 20.0 * Math.sin(2.0 * x * pi)) * 2.0) / 3.0
		ret += ((20.0 * Math.sin(x * pi) + 40.0 * Math.sin((x / 3.0) * pi)) * 2.0) / 3.0
		ret += ((150.0 * Math.sin((x / 12.0) * pi) + 300.0 * Math.sin((x / 30.0) * pi)) * 2.0) / 3.0
		return ret
	}

	function transformLat(x, y) {
		var pi = Math.PI
		var ret = -100.0 + 2.0 * x + 3.0 * y + 0.2 * y * y + 0.1 * x * y + 0.2 * Math.sqrt(Math.abs(x))
		ret += ((20.0 * Math.sin(6.0 * x * pi) + 20.0 * Math.sin(2.0 * x * pi)) * 2.0) / 3.0
		ret += ((20.0 * Math.sin(y * pi) + 40.0 * Math.sin((y / 3.0) * pi)) * 2.0) / 3.0
		ret += ((160.0 * Math.sin((y / 12.0) * pi) + 320 * Math.sin((y * pi) / 30.0)) * 2.0) / 3.0
		return ret
	}

	if (outOfChina(lon, lat)) {
		return [lon, lat]
	} else {
		var dLat = transformLat(lon - 105.0, lat - 35.0)
		var dLon = transformLon(lon - 105.0, lat - 35.0)
		var radLat = (lat / 180.0) * Math.PI
		var magic = Math.sin(radLat)
		magic = 1 - ee * magic * magic
		var sqrtMagic = Math.sqrt(magic)
		dLat = (dLat * 180.0) / (((a * (1 - ee)) / (magic * sqrtMagic)) * Math.PI)
		dLon = (dLon * 180.0) / ((a / sqrtMagic) * Math.cos(radLat) * Math.PI)
		var mgLat = lat + dLat
		var mgLon = lon + dLon
		return [lon * 2 - mgLon, lat * 2 - mgLat]
	}
}

Vue.prototype.$hideLoading = debounce(function () {
	uni.hideLoading()
}, 50)

Vue.prototype.$base64ToPath = base64ToPath

Vue.prototype.$pathToBase64 = pathToBase64

// 获取剩余高度
Vue.prototype.$getHeight = (navClassName) => {
	return new Promise((resolve) => {
		// 获取屏幕高度
		uni.getSystemInfo({
			success: (res) => {
				let windowHeight = res.windowHeight
				if (!navClassName) {
					resolve(windowHeight)
					return
				}

				let view = uni.createSelectorQuery().select(navClassName)
				view
					.boundingClientRect((data) => {
						// console.log('tabInList基本信息 = ' + data.height)
						let screenHeightLeast = windowHeight - data.height
						resolve(screenHeightLeast)
					})
					.exec()
			}
		})
	})
}

Vue.prototype.$share = (domId) => {
	try {
		uni.showToast({
			title: '正在生成海报',
			icon: 'none',
			mask: true,
			duration: 100000
		})
		return new Promise((resolve) => {
			const timeout = setTimeout(async () => {
				const shareContent = document.querySelector(domId)
				const canvas = await html2canvas(shareContent, {
					width: shareContent.offsetWidth, //设置canvas尺寸与所截图尺寸相同，防止白边
					height: shareContent.offsetHeight, //防止白边
					logging: true,
					useCORS: true
				})
				const base64 = canvas.toDataURL('image/jpeg', 1)
				uni.hideToast()
				clearTimeout(timeout)
				resolve(base64)
			}, 500)
		})
	} catch (error) {
		console.log(error)
	}
}
// 跳转到到当前程序页面
Vue.prototype.$toUrl = (url, data) => {
	let urlPast = url
	if (data) {
		urlPast += '?data=' + encodeURIComponent(JSON.stringify(data))
		console.info(`urlPast:`, urlPast)
	}
	uni.navigateTo({
		url: urlPast
	})
}
Vue.filter('dateStr', function (dataStr, pattern = 'YYYY-MM-DD HH:mm:ss') {
	if (!dataStr) {
		return moment().format(pattern)
	} else {
		return moment(dataStr).format(pattern)
	}
})

// 检测地图是否渲染
const checkNum = (oldNum) => {
	return new Promise((resolve) => {
		const outT = setTimeout(() => {
			clearInterval(interT)
			clearTimeout(outT)
			resolve(false)
		}, 1500)
		const interT = setInterval(() => {
			if (oldNum < window.getLocationNum) {
				console.info(`请求:请求请求请求请求`)

				clearInterval(interT)
				clearTimeout(outT)
				resolve(true)
			}
		}, 100)
	})
}
Vue.prototype.$getLocation = (navClassName) => {
	return new Promise(async (resolve) => {
		// if (!latlon) {
		// 	uni.getLocation({
		// 		type: 'gcj02',
		// 		success: async (res) => {
		// 			console.info(`requestFullScreen:`, res)
		// 			// resolve(res)
		// 			let latLon = gcj02_To_gps84(res.longitude, res.latitude)
		// 			resolve({
		// 				longitude: latLon.lng,
		// 				latitude: latLon.lat
		// 			})
		// 		}
		// 	})
		// }
		uni.webView.postMessage({
			data: {
				message: 'getLocation',
				data: 'resp'
			}
		})
		const res = await checkNum(window.getLocationNum)
		// console.info(`res:`, res)
		if (res) {
			const latlon = uni.getStorageSync('latlon')
			resolve(latlon)
		} else {
			uni.getLocation({
				type: 'wgs84',
				success: async (res) => {
					// console.info(`requestFullScreen:`, res)
					// resolve(res)
					let latLon = gcj02_To_gps84(res.longitude, res.latitude)
					resolve({
						longitude: latLon.lng,
						latitude: latLon.lat
					})
				}
			})
		}
	})
}

// #ifdef H5
// if (uni.getSystemInfoSync().platform != "ios") {
var script = document.createElement('script')
script.src = '../static/js/hls.js@latest'
script.onload = function () {
	let init = function (video) {
		if (!video.getAttribute('hls-inited')) {
			let hls = null
			let load = function () {
				let src = video.src
				if (!src || src.indexOf('.m3u8') < 0) return
				if (!hls) {
					hls = new Hls()
					hls.attachMedia(video)
				}
				hls.loadSource(src)
			}
			video.addEventListener(
				'error',
				function () {
					load()
				},
				false
			)
			video.addEventListener(
				'DOMNodeRemovedFromDocument',
				function () {
					if (hls) {
						hls.destroy()
					}
				},
				false
			)
			video.setAttribute('hls-inited', 'ok')
		}
	}

	let list = Array.from(document.getElementsByTagName('video'))
	list.forEach(init)
	document.body.addEventListener('DOMNodeInserted', function (e) {
		let ele = e.relatedNode
		if (ele.tagName === 'VIDEO') {
			init(ele)
		}
		let eleList = Array.from(ele.getElementsByTagName('video'))
		eleList.forEach(init)
	})
}
var s = document.getElementsByTagName('script')[0]
s.parentNode.insertBefore(script, s)
// }

// var plusReady = function (callback) {
// 	if (window.plus) {
// 		callback()
// 	} else {
// 		document.addEventListener('plusready', callback)
// 	}
// }
// plusReady(function () {
// 	var firstBack = 0
// 	var handleBack = function () {
// 		var currentWebview = plus.webview.currentWebview() //当前窗口
// 		console.log('currentWebview', currentWebview)
// 		var now =
// 			Date.now ||
// 			function () {
// 				return new Date().getTime()
// 			}
// 		currentWebview.canBack(function (evt) {
// 			/**
// 			 * 有可后退的历史记录，则后退。
// 			 * 否则，关闭当前窗口。
// 			 */
// 			console.info(`evt:`, evt.canBack)
// 			// 有回退的页面
// 			if (evt.canBack) {
// 				history.back()
// 			} else {
// 				// 没有回退页面
// 				// firstBack 为0时 第一次返回
// 				if (!firstBack) {
// 					// 第一次返回时间
// 					firstBack = now()
// 					// 信息提示
// 					plus.nativeUI.toast('再按一次退出应用')
// 					setTimeout(function () {
// 						firstBack = 0
// 					}, 2000)
// 					//第二次点击返回 直接退出应用
// 				} else if (now() - firstBack < 2000) {
// 					plus.runtime.quit()
// 				}
// 			}
// 		})
// 	}
// 	plus.key.addEventListener('backbutton', handleBack)
// })
// #endif

// echart问题
// window.wx = undefined

Vue.filter('meteoValue', function (value, otherNamePost) {
	let otherName = '-'
	if (value == 0) {
		return 0
	}
	if (otherNamePost) {
		let number = JSON.parse(JSON.stringify(otherNamePost))
		let num = Math.abs(parseInt(number))
		otherName = [999, 9999].includes(num) ? '-' : otherNamePost
	}
	let text = value
	// 不存在
	if (!value) {
		return otherName
	}
	// 存在999，-9999，9999，999，999.0，999.00等情况一律处理掉
	let intNum = Math.abs(parseInt(value))
	if (intNum == 999 || intNum == 9999) {
		return otherName
	}
	return text
})

// 移除缓存
Vue.prototype.$removeItem = (key) => {
	uni.removeStorageSync(key)
}
// 获取缓存
Vue.prototype.$getItem = (key) => {
	return uni.getStorageSync(key)
}
// 设置缓存
Vue.prototype.$setItem = (key, value) => {
	uni.setStorageSync(key, value)
}
// 清楚缓存
Vue.prototype.$clearItem = () => {
	uni.clearStorageSync()
}
